package com.wyz.demo;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个是使用 阿里巴巴的开源的TransmittableThreadLocal 实现线程间数据传递
 */
public class TransmittableThreadLocalExample {
    private static final TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();

    public static void main(String[] args) {
//        ExecutorService executor = Executors.newFixedThreadPool(2);
//
//        transmittableThreadLocal.set("Parent Thread Value");
//
//        // 提交任务到线程池
//        executor.submit(() -> {
//            System.out.println("Child Thread: " + transmittableThreadLocal.get());
//        });
//        transmittableThreadLocal.set("Parent Thread new  Value");
//        executor.submit(() -> {
//            System.out.println("Child Thread: " + transmittableThreadLocal.get());
//        });
//        executor.submit(() -> {
//            System.out.println("Child Thread: " + transmittableThreadLocal.get());
//        });
//        executor.shutdown();

        /**
         * 输出：
         * Child Thread: Parent Thread Value
         * Child Thread: Parent Thread new  Value
         * Child Thread: Parent Thread Value
         */

        ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(2));
        transmittableThreadLocal.set("Parent Thread Value");

        // 提交任务到线程池
        ttlExecutorService.submit(() -> {
            System.out.println("Child Thread: " + transmittableThreadLocal.get());
        });
        transmittableThreadLocal.set("Parent Thread new  Value");
        ttlExecutorService.submit(() -> {
            System.out.println("Child Thread: " + transmittableThreadLocal.get());
        });
        ttlExecutorService.submit(() -> {
            System.out.println("Child Thread: " + transmittableThreadLocal.get());
        });
        /**
         * 输出结果：
         * Child Thread: Parent Thread Value
         * Child Thread: Parent Thread new  Value
         * Child Thread: Parent Thread new  Value
         */
    }
}